The function pivot_longer() longifys data, converting it from wide to long. Long data is generally the preferred format for Tidyverse, and is especially useful for ggplot2.
When data is longified:
The number of rows increases.
The number of columns decreases.
To longify data a set of columns are chosen.
The column names are assigned as data of a names column.
The values within the columns are assigned to a value column. Each value is within its own row.
#Load packagelibrary("mgrtibbles")#fisheries_wide_tbl tibble for demonstrationmgrtibbles::fisheries_wide_tbl |>#View first 11 columns with select dplyr::select(1:11)
# A tibble: 1,872 × 7
CCA3 `Country/Territory` Capital Continent Area_km2 Year Population
<fct> <fct> <chr> <fct> <dbl> <chr> <dbl>
1 AFG Afghanistan Kabul Asia 652230 2022 41128771
2 AFG Afghanistan Kabul Asia 652230 2020 38972230
3 AFG Afghanistan Kabul Asia 652230 2015 33753499
4 AFG Afghanistan Kabul Asia 652230 2010 28189672
5 AFG Afghanistan Kabul Asia 652230 2000 19542982
6 AFG Afghanistan Kabul Asia 652230 1990 10694796
7 AFG Afghanistan Kabul Asia 652230 1980 12486631
8 AFG Afghanistan Kabul Asia 652230 1970 10752971
9 ALB Albania Tirana Europe 28748 2022 2842321
10 ALB Albania Tirana Europe 28748 2020 2866849
# ℹ 1,862 more rows
Note: Quotes are used for 2022 and 1970 as column/variable names that are numbers need them or they will not work.